﻿using System;
using System.Globalization;
using System.IO;
using System.Xml;
using System.Xml.Serialization;

namespace TK.Common.Tools
{
    /// <summary>
    /// XmlConverter
    /// </summary>
    public class XmlConverter
    {
        /// <summary>
        /// Serialize
        /// </summary>
        public static string Serialize<T>(T obj)
        {
            try
            {
                using var writer = new StringWriter(CultureInfo.InvariantCulture);
                var serializer = new XmlSerializer(typeof(T));
                serializer.Serialize(writer, obj);
                return writer.ToString();
            }
            catch (Exception)
            {
                return null;
            }
        }

        /// <summary>
        /// Deserialize
        /// </summary>
        public static T Deserialize<T>(string xml)
        {
            try
            {
                using var reader = new StringReader(xml);
                using var xmlReader = XmlReader.Create(reader);
                var serializer = new XmlSerializer(typeof(T));
                return (T)serializer.Deserialize(xmlReader);
            }
            catch (Exception)
            {
                return default;
            }
        }

        /// <summary>
        /// SelectSingleNode
        /// </summary>
        public static XmlElement GetRootNode(string xml)
        {
            try
            {
                var doc = new XmlDocument
                {
                    //解析外部XML需要设置为空，防止产生XFX漏洞攻击
                    XmlResolver = null
                };
                doc.LoadXml(xml);

                return doc.DocumentElement;
            }
            catch (Exception)
            {
                return null;
            }
        }
    }
}
